# Copyright (c) 2025 Huawei Technologies Co. Ltd.
# deepinsight is licensed under Mulan PSL v2.
# You can use this software according to the terms and conditions of the Mulan PSL v2.
# You may obtain a copy of Mulan PSL v2 at:
#          http://license.coscl.org.cn/MulanPSL2
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
# EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
# MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
# See the Mulan PSL v2 for more details.
import os
from fastapi import Depends
from starlette.requests import HTTPConnection

from deepinsight.service.auth.base import AuthManager
from deepinsight.service.auth.openeuler_intelligence.session_service import UserHTTPException


async def get_current_user(request: HTTPConnection):
    """
    获取当前用户的依赖项

    此函数会先检查环境变量是否需要认证，不需要则直接返回admin
    需要认证时会使用配置的认证提供者验证用户身份，并将用户信息添加到请求对象中
    可作为依赖项在路由处理函数中使用
    """
    try:
        # 检查环境变量是否需要认证鉴权，默认需要
        need_auth = os.getenv("REQUIRE_AUTHENTICATION", "true").lower() != "false"

        # 如果不需要认证，直接返回默认用户admin
        if not need_auth:
            request.state.user = "admin"
            return "admin"

        # 获取配置的认证提供者
        auth_provider = AuthManager.get_provider()

        # 验证用户凭证
        if not await auth_provider.verify_credentials(request):
            raise UserHTTPException(
                status_code=401,
                retcode=401,
                rtmsg="Authentication Error: Invalid credentials",
                data=""
            )

        # 获取用户ID
        user_id = await auth_provider.get_user_id(request)

        # 将用户信息添加到请求状态中
        request.state.user = user_id
        return user_id

    except UserHTTPException:
        raise
    except Exception as e:
        raise UserHTTPException(
            status_code=401,
            retcode=401,
            rtmsg=f"Authentication Error: {str(e)}",
            data=""
        )


# 用于需要验证用户的路由的装饰器依赖
require_user = Depends(get_current_user)
